package com.mijie.homi.ns.core.handler;

import java.util.Date;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.mina.core.session.IoSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.mijie.homi.common.constant.CategoryCode;
import com.mijie.homi.common.constant.TypeCode;
import com.mijie.homi.common.domain.chat.ChatMessage;
import com.mijie.homi.common.protocol.HomiProtocol;
import com.mijie.homi.ns.core.HomiServer;
import com.mijie.homi.ns.service.ChatService;
import com.mijie.homi.ns.traffic.MessageRouter;
import com.mijie.util.Helper;

@Service
public class ChatHandler implements Handler{

	@Autowired
	private ChatService chatService;
	
	public Object handler(IoSession session,HomiProtocol protocol){
		Integer sender = HomiServer.getUserId(session);
		//already login
		if(sender!=null){
			JSONObject json = JSONObject.fromObject(new String(protocol.getContent()));
			if(json.containsKey("category")){
				json.put("sender", sender);
				int category = json.getInt("category");
				switch(category){
				case CategoryCode.CHAT_VOICE:
				case CategoryCode.CHAT_TEXT_MESSAGE:
				case CategoryCode.CHAT_GIF:
					boolean blocked = chatService.blockingMessage(json.getInt("receiver"), sender);
					if(blocked){
						HomiProtocol feedbackPack = new HomiProtocol(TypeCode.CHAT);
						JSONObject feedbackJson = new JSONObject();
						feedbackJson.accumulate("cid", json.getString("cid"));
						feedbackJson.accumulate("createAt", new Date().getTime());
						feedbackJson.accumulate("category", CategoryCode.CHAT_SEND_STATUS_BLOCKED);
						feedbackPack.setContent(feedbackJson.toString());
						session.write(feedbackPack);
					}else{
						HomiProtocol feedbackPack = new HomiProtocol(TypeCode.CHAT);
						JSONObject feedbackJson = new JSONObject();
						feedbackJson.accumulate("cid", json.getString("cid"));
						feedbackJson.accumulate("createAt", new Date().getTime());
						feedbackJson.accumulate("category", CategoryCode.CHAT_SEND_STATUS_SUCCESS);
						feedbackPack.setContent(feedbackJson.toString());
						session.write(feedbackPack);
						
						chatService.sendChatMessage(sender,json);
					}
					break;
				case CategoryCode.CHAT_RECEIVE_REPORT:
					JSONArray ids = json.getJSONArray("ids");
					if(ids!=null){
						String[] list = new String[ids.size()];
						for(int i=0;i<list.length;i++)
							list[i] = ids.getString(i);
						chatService.deleteChatMessage(list);
					}
					break;
				}
			}
		}
		return null;
	}

}
